import React, { useEffect, useRef } from 'react';
import Modals from '@/components/modals/Modals';
import { ConfigProvider, Form, Input, TreeSelect, ModalProps } from 'antd';
import { CreateGroupReq, GetGroupTreeList, UpdateGroupReq } from '@/common';
import { LONG_TEXT, SHORT_TEXT } from '@/common/app/constants';

const { TextArea } = Input;

interface orgDefaultData {
  id?: string;
  name: string;
  parent_id: string;
  description: string;
  level?: number;
}
interface Props extends ModalProps {
  title: string;
  onSubmitOk: (values: CreateGroupReq | UpdateGroupReq, type: boolean) => void;
  onCancel: () => void;
  open: boolean;
  state: boolean;
  defaultValue: orgDefaultData;
  treeData: GetGroupTreeList[];
}

const AddOrDditOrganiztionalModal = ({
  title,
  onSubmitOk,
  onCancel,
  open,
  defaultValue,
  treeData,
  state,
  ...props
}: Props) => {
  const [form] = Form.useForm();
  const data = useRef<GetGroupTreeList>();

  useEffect(() => {
    if (form && defaultValue) {
      form.setFieldsValue(defaultValue);
    }
  }, [defaultValue]);

  const onSubmit = () => {
    form.submit();
  };

  const onFinish = (values: CreateGroupReq) => {
    if (!state) {
      if (data.current) {
        values = { ...values, parent_id: data.current?.id, id: defaultValue.id };
      } else {
        values = { ...values, parent_id: defaultValue?.parent_id as string, id: defaultValue.id };
      }
    }
    onSubmitOk(values, state);
    data.current = undefined;
  };

  const findValue = (data: GetGroupTreeList[], value: string): GetGroupTreeList | undefined => {
    for (let i = 0; i < data.length; i++) {
      // 如果当前节点的值符合条件，立即返回
      if (data[i].id === value) {
        return data[i];
      }
      // 如果子节点存在，递归调用
      if (data[i].children) {
        const result = findValue(data[i].children, value);
        if (result) {
          return result; // 如果在子节点中找到，立即返回
        }
      }
    }
    // 如果没有找到，返回 undefined
    return undefined;
  };

  const changeTreeSelect = (value: any) => {
    const result = findValue(treeData, value);
    data.current = result;

    let temp = {
      parent_id: result?.id,
    };
    form.setFieldsValue(temp);
  };

  return (
    <Modals {...props} title={title} open={open} onOk={onSubmit} onCancel={onCancel}>
      <ConfigProvider
        theme={{
          components: {
            Form: {
              labelColor: '#474C5F',
            },
          },
        }}
      >
        <Form layout="vertical" onFinish={onFinish} form={form}>
          {defaultValue?.level !== 0 && (
            <Form.Item
              label="所属组织"
              name={'parent_id'}
              rules={[{ required: true, message: '请选择你所属的组织!' }]}
            >
              <TreeSelect
                placeholder="请选择所属组织"
                treeData={treeData}
                className="custom-select"
                treeDefaultExpandAll
                onChange={changeTreeSelect}
                fieldNames={{
                  label: 'name',
                  value: 'id',
                  children: 'children',
                }}
              />
            </Form.Item>
          )}

          <Form.Item
            label="组织名称"
            name="name"
            rules={[
              { required: true, message: '请输入组织名称!' },
              { max: SHORT_TEXT, message: `上限字数为${SHORT_TEXT}个` },
              {
                validator: (_, value) =>
                  value && value.trim() !== ''
                    ? Promise.resolve()
                    : Promise.reject('组织名称不能全为空格!'),
              },
            ]}
          >
            <Input placeholder="请输入名称" className="!border-0 !bg-input-gray !text-base" />
          </Form.Item>

          <Form.Item
            label="组织职责(选填)"
            name="description"
            rules={[{ max: LONG_TEXT, message: `上限字数为${LONG_TEXT}个` }]}
          >
            <TextArea
              showCount
              placeholder="请输入组织的职责,能更好的帮助系统遇到位置问题时进行分类"
              className="!border-0 !bg-input-gray !text-base"
              autoSize={{ minRows: 8, maxRows: 8 }}
              maxLength={LONG_TEXT}
            />
          </Form.Item>
        </Form>
      </ConfigProvider>
    </Modals>
  );
};

export default AddOrDditOrganiztionalModal;
